format.py
= 42
my_num
print(my_num)
Being able to print things to the screen is a fundamental part of interacting with a programming language. So far, we’ve kept it simple by passing the data we want to print directly to the print
function:
format.py
= 42
my_num
print(my_num)
Terminal/Command Prompt
python format.py
42
We made things a bit nicer by using the fact that if you pass multiple arguments to print
then it will print each of them, separated by spaces, allowing us to combine our data with a message:
format.py
= 42
my_num
print("My num is", my_num)
Terminal/Command Prompt
python format.py
My num is 42
This works perfectly well but firstly you’re using the implicit space that’s added by print
as part of your sentence and secondly you’re passing in two separate pieces of information where they are logically one.
What we can do instead is create a single string which contains the message we want to print and put special placeholders inside it where we want our data to appear. There’s a few different ways to do this in Python (an older but still valid method you may see uses %
and another uses a format()
function) but for this course we will use the method called f-strings which was introduced in Python 3.6 (released December 2016).
If you put a single f
directly in front of the string that you are creating, it will enable a special string mode which lets you place {}
inside the string with a variable name between the {
and the }
:
format.py
= 42
my_num
print(f"My num is {my_num}")
Terminal/Command Prompt
python format.py
My num is 42
You can have as many interpolations as you like:
format.py
= 42
answer = 3.14159
pi
print(f"The answer is {answer} and pi is {pi}")
Terminal/Command Prompt
python format.py
The answer is 42 and pi is 3.14159